<!-- 库存表 -->
<template>
    <div>
        <div class="admin-statistics-content">
            <div class="item e-flex-1">
                <label>库存重量</label>
                <div class="e-m-t-10"><span class="num">{{ summary.weight }}</span><small>KG</small></div>
            </div>
            <div class="item e-flex-1">
                <label>库存数量</label>
                <div class="e-m-t-10"><span class="num">{{ summary.quantity }}</span><small>件</small></div>
            </div>
            <div class="item e-flex-1">
                <label>库存价值</label>
                <div class="e-m-t-10"><span class="num">{{ summary.amount }}</span><small>元</small></div>
            </div>
        </div>

        <el-table ref="multipleTable" tooltip-effect="dark" :data="tableData" :span-method="objectSpanMethod" stripe
            border style="width: 100%; margin-top: 20px">
            <el-table-column prop="large" label="类型">
            </el-table-column>
            <el-table-column prop="name" label="可回收物">
                <template slot-scope="scope">
                    <span>{{ scope.row.name }}{{ scope.row.isweighing ? '' : '（按件）' }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="weight" label="总量">
                <template slot-scope="scope">
                    <span>{{ scope.row.weight }}{{ scope.row.isweighing ? 'KG' : '件' }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="180" v-if="innerStoreid > 0">
                <template slot-scope="scope">
                    <el-button type="text" size="small"
                        @click="$router.push({ path: '/inventory/views?productId=' + scope.row.id + '&storeId=' + innerStoreid })">查看</el-button>
                    <el-button type="text" size="small" @click="startStockAdjust(scope.row)">调整库存</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 调整库存 -->
        <el-dialog title="调整库存" :visible.sync="dialogVisible" width="800px" z-index="99">
            <el-form :model="stockAdjust" label-width="70px">
                <el-form-item label="增减库存" prop="title">
                    <el-input type="number" :placeholder="`输入增减${stockAdjust.typeNames}的库存，填正数为增加，负数为减少`"
                        v-model="stockAdjust.weight"></el-input>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input type="textarea" v-model="stockAdjust.reason" :rows="4"></el-input>
                </el-form-item>
            </el-form>
            <div class="tips">
                <div style="text-indent: 2em;">注：此操作为手动增减或减少当前小类的库存；增减库存填正数为增加，负数为减少</div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" :loading="loading" @click="handleStockAdjust">调整</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    props: {
        storeId: {
            type: Number,
            default: 0
        }
    },
    data() {
        return {
            loading: false,
            tableData: [],
            innerStoreid: this.storeId == 0 ? "" : this.storeId,
            StoreList: '',
            summary: {
                weight: 0,
                quantity: 0,
                amount: 0
            },
            /* 调整库存 */
            dialogVisible: false,
            stockAdjust: {
                typeNames: '',
                largeTypeWeight: null,
                storeId: 0,
                typeId: 0,
                productId: 0,
                weight: null,
                reason: '',
                isweighing: false,
                targetSmallTypeName: '',
                targetLargeTypeId: 0,
                targetLargeTypeIsweighing: false,
                targetSmallTypeWeight: null,
                targetSmallId: 0,
                targetWeight: null,
            },
            chooseType: [],
            tempSmallTypeList: []
        };
    },
    watch: {
        storeId(val) {
            console.log('storeId changed:', val, 'type:', typeof val)
            this.innerStoreid = val
            this.getlist()
        },
        dialogVisible(val) {
            if (val) {
                this.chooseType = []

            } else {
                this.stockAdjust = {
                    typeNames: '',
                    largeTypeWeight: null,
                    storeId: 0,
                    typeId: 0,
                    productId: 0,
                    weight: null,
                    reason: '',
                    isweighing: false,
                    targetSmallTypeName: '',
                    targetLargeTypeId: 0,
                    targetLargeTypeIsweighing: false,
                    targetSmallTypeWeight: null,
                    targetSmallId: 0,
                    targetWeight: null,
                }
            }
        }
    },
    mounted() {
        console.log('storeId:', this.storeId, this.innerStoreid)
        console.log('/Statistics/StockOverview:', localStorage.getItem('lifeData'))

        this.getlist()
    },
    methods: {
        objectSpanMethod({
            row,
            column,
            rowIndex,
            columnIndex
        }) {
            // console.log(rowIndex, columnIndex,'ssss')
            // console.log(row, 'aaaaa')

            let mergeLength = 1; //需要进行横纵合并的列
            if (columnIndex < mergeLength) {
                let finArray = [1, 1];
                // 处理行数据
                // let cgname = Object.keys(row)[0] //7是数字最后一项类型id
                let cgname = 'large' //合并单元格的主键依据，一般为第一列的值
                if (rowIndex === 0 || row[cgname] !== this.tableData[rowIndex - 1][cgname]) {
                    let rowspan = 1;
                    //计算需要进行合并操作的行
                    for (let i = 0; i < this.tableData.length - 1; i++) {
                        // 只合并连续的
                        if (this.tableData[i][cgname] === row[cgname] && this.tableData[i + 1][cgname] === row[
                            cgname]) {
                            rowspan++;
                        }
                    }
                    finArray[0] = rowspan;
                } else {
                    finArray[0] = 0;
                }
                return finArray
            }
        },
        flattenData(data, level = 0, parentPath = []) {
            let result = [];
            data.forEach(item => {
                const currentPath = [...parentPath, item];
                item.product.forEach(product => {
                    result.push({
                        id: product.id,
                        name: product.name,
                        isweighing: product.isweighing,
                        weight: product.weight,
                        large: item.name,
                        bigid: item.id,
                        level: level,
                        isCategory: true,
                    });
                })
                // 递归处理子类型
                if (item.type && item.type.length > 0) {
                    // console.log(currentPath)
                    const childData = this.flattenData(item.type, level + 1, currentPath);
                    console.log('递归处理子类型-childData:', childData)
                    childData.forEach((cell) => {
                        result = result.concat([{
                            id: cell.id,
                            name: `${cell.large}-${cell.name}`,
                            // name: this.getSubCategoryName(currentPath),
                            isweighing: cell.isweighing,
                            weight: cell.weight,
                            large: currentPath[0].name,
                            bigid: currentPath[0].id,
                            level: cell.level,
                            isCategory: cell.isCategory,
                        }]);
                    })

                }
            })
            return result;
        },
        getlist() {
            this.tableData = []
            this.$axios.post(`/Statistics/StockOverview`, {
                operatorid: JSON.parse(localStorage.getItem('lifeData')).operatorid,
                storeIds: this.storeId?[this.storeId]:[]
            }).then(res => {
                this.tableData = this.flattenData(res.type)
                this.summary.weight = res.weight
                this.summary.quantity = res.quantity
                this.summary.amount = res.amount
                console.log(this.tableData)
                this.loading = false

            })
        },
        // 获取子分类名称（除第一级外的所有级别）
        getSubCategoryName(path) {
            if (path.length <= 1) return ''; // 只有一级分类时为空

            // 从第二级开始的所有分类名称
            const subNames = path.slice(1).map(item => item.name);
            return subNames.join(' - ');
        },
        SelectType(v) { //选择品类
            this.stockAdjust.targetLargeTypeId = v[0]
            this.stockAdjust.targetSmallId = v[1]
            this.stockAdjust.targetSmallTypeName = this.tempSmallTypeList?.find((item) => item.id == this.stockAdjust
                .targetSmallId)?.name
            this.stockAdjust.targetSmallTypeWeight = this.tempSmallTypeList?.find((item) => item.id == this.stockAdjust
                .targetSmallId)?.weight || 0
            this.stockAdjust.targetLargeTypeIsweighing = this.tempSmallTypeList?.find((item) => item.id == this
                .stockAdjust.targetSmallId)?.isweighing
        },
        loadType(node, resolve) { //加载品类
            const {
                level
            } = node;
            if (level == 0) {
                this.$axios.get('/Waste/Type/List', {
                    pageIndex: 1,
                    pageSize: 9999,
                    pId: 0
                }).then((res) => {
                    node = res.map(function (c) {
                        return {
                            id: c.id,
                            name: c.name,
                            leaf: level >= 1
                        }
                    });
                    resolve(node);
                })
            } else {
                if (level == 1) {
                    this.$axios.get(`/Waste/product/List`, {
                        params: {
                            typeId: node.value
                        }
                    }).then((res) => {
                        node = res.map(function (c) {
                            return {
                                id: c.id,
                                name: c.name,
                                leaf: level >= 1
                            }
                        });
                        this.tempSmallTypeList = node
                        resolve(node);
                    })
                } else {
                    resolve();
                }
            }
        },
        startStockAdjust(item) { //点击调整库存
            if (!this.innerStoreid) {
                this.$message({
                    message: '请选择站点后再操作',
                    type: 'error'
                })
                return
            }
            this.stockAdjust.storeId = this.innerStoreid
            this.stockAdjust.typeNames = item.name
            this.stockAdjust.largeTypeWeight = item.weight
            this.stockAdjust.typeId = item.bigid
            this.stockAdjust.productId = item.id
            this.stockAdjust.isweighing = item.isweighing
            this.dialogVisible = true
        },
        handleStockAdjust() { //提交库存调整
            this.$axios.post('/Store/Stock/Adjust', {
                storeId: this.stockAdjust.storeId,
                details: [
                    {
                        "productId": this.stockAdjust.productId,
                        "weight": this.stockAdjust.weight,
                        "reason": "1"
                    }
                ]
            }).then((res) => {
                this.$message({
                    message: '库存调整成功',
                    type: 'success'
                })
                this.dialogVisible = false
                this.dialogVisible2 = false
                this.getlist()
            })
        }
    }
}
</script>

<style lang="scss" scoped>
    .admin-statistics-content {
        display: flex;
        background-color: #fff;
        padding: 15px;
        height: calc(100% - 30px);
        border: 1px solid var(--light);

        .item {
            &+.item {
                border-left: 1px solid var(--light);
                padding-left: 30px;
            }

            .icon {
                width: 44px;
                height: 44px;
                border-radius: 50%;
                border: 1px solid var(--light);
                background-color: #f2f3f5;
                padding: 5px;
                margin: 0 20px 0 0;
                box-shadow: 3px 2px 11px 0 rgb(70 70 70 / 22%);
            }

            label {
                color: var(--grey);
                font-size: 12px;
                margin-bottom: 5px;
                display: block;
            }

            .num {
                font-size: 30px;
            }
        }
    }
</style>